package org.example.judge_comment.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.judge_comment.entity.RequestMailParams;
import org.example.judge_comment.service.MailService;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.util.MailClient;
import org.example.judge_pojo.Auth;
import org.example.judge_pojo.Mail;
import org.example.judge_pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/comment/mail")
public class MailController {

    @Qualifier("MailServiceImpl")
    @Autowired
    private MailService mailService;



    @AuthAnnotation({Auth.CLIENT})
    @PostMapping("/search")
    public ResponseResult list(RequestMailParams params){

        PageResult<Mail> res = mailService.search(params);
        return ResponseResult.success().setData(res);
    }

    @AuthAnnotation({Auth.CLIENT})
    @PostMapping("/save")
    public ResponseResult save(@RequestBody Mail mail, HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        if(loginUser!=null)mail.setUserId(loginUser.getId());
        mailService.save(mail);
        return ResponseResult.success();
    }

    /**
     * 标记已读
     * @param id
     * @param request
     * @return
     */
    @AuthAnnotation({Auth.CLIENT})
    @PostMapping("/read")
    public ResponseResult save(@RequestParam String id, HttpServletRequest request){

        if("1".equals(id)){ //系统消息标记处理
            User loginUser = (User) request.getAttribute("loginUser");
            mailService.update(new UpdateWrapper<Mail>().eq("user_id",id).eq("`to`",loginUser.getId())
                    .set("`read`",1));
        }else
            mailService.update(new UpdateWrapper<Mail>().eq("id",id).set("`read`",1));
        return ResponseResult.success();
    }
    @AuthAnnotation({Auth.CLIENT})
    @DeleteMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable("id") String id,HttpServletRequest request){
        Mail byId = mailService.getById(id);
        User loginUser = (User) request.getAttribute("loginUser");

        if(!Auth.isAdmin(loginUser)) {
            if(loginUser.getId().equals(byId.getUserId())&&byId.getUserId().equals("1"))
                return ResponseResult.unAuditor(); //只能删除系统消息
        }
        mailService.removeById(id);
        return ResponseResult.success();
    }
}
